package OnlineShopping;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class Customer extends User{
    ShoppingCart shoppingCart;
    private HistoryRecord historyRecord;
    private String password;
    private String username;
    private String userId;
    private int loginAttempts;
    private  boolean isLocked;

    public Customer(String userId, String username, String password, String email, String phone,
                    String registrationDate, String userLevel, double totalSpent, HistoryRecord history,
                    ShoppingCart shoppingCart, HistoryRecord historyRecord, String password1,
                    String username1, String userId1, int loginAttempts, boolean isLocked) {
        super(userId, username, password, email, phone, registrationDate, userLevel, totalSpent, history);

        this.password = password1;
        this.username = username1;
        this.userId = userId1;
        this.shoppingCart = new ShoppingCart();
        this.historyRecord = new HistoryRecord();
        this.loginAttempts = 0; // 初始化为 0
        this.isLocked = false; // 默认账户未锁定
    }

    public Customer(String userId, String username, String password, String email, String phone, String registrationDate, String userLevel, double totalSpent, HistoryRecord history) {
        super(userId, username, password, email, phone, registrationDate, userLevel, totalSpent, history);
    }

    public Customer() {
        super("defaultId", "defaultUser", "defaultPass", "defaultEmail", "defaultPhone", "defaultDate", "defaultLevel", 0, new HistoryRecord());
        this.shoppingCart = new ShoppingCart();
        this.historyRecord = new HistoryRecord();
    }

    public ShoppingCart getShoppingCart() {
        return shoppingCart;
    }

    public void setShoppingCart(ShoppingCart shoppingCart) {
        this.shoppingCart = shoppingCart;
    }

    public HistoryRecord getHistoryRecord() {
        return historyRecord;
    }

    public void setHistoryRecord(HistoryRecord historyRecord) {
        this.historyRecord = historyRecord;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public int getLoginAttempts() {
        return loginAttempts;
    }

    public void setLoginAttempts(int loginAttempts) {
        this.loginAttempts = loginAttempts;
    }

    public boolean isLocked() {
        return isLocked;
    }

    public void setLocked(boolean locked) {
        isLocked = locked;
    }

    //登录
    public boolean login(String username, String password) {
        if (isLocked) {
            System.out.println("账户已被锁定，请联系管理员解锁。");
            return false;
        }

        try (FileInputStream fis = new FileInputStream("E:\\Desktop\\大二上\\实训\\网上购物系统\\Customer.xlsx");
             Workbook workbook = new XSSFWorkbook(fis)) {
            Sheet sheet = workbook.getSheetAt(0);
            DataFormatter dataFormatter = new DataFormatter(); // 创建 DataFormatter 实例

            for (Row row : sheet) {
                Cell usernameCell = row.getCell(1); // 假设用户名在第二列
                Cell passwordCell = row.getCell(7); // 假设密码在第八列
                Cell lockedCell = row.getCell(8); // 假设锁定状态在第九列

                // 使用 DataFormatter 获取单元格的字符串值
                String usernameValue = dataFormatter.formatCellValue(usernameCell).trim();
                String passwordValue = dataFormatter.formatCellValue(passwordCell).trim();
                String lockedValue = dataFormatter.formatCellValue(lockedCell).trim();

                if (usernameValue.equals(username) && passwordValue.equals(password)) {
                    if ("是".equals(lockedValue)) {
                        System.out.println("账户已被锁定，请联系管理员解锁。");
                        return false; // 账户已锁定
                    }

                    this.userId = dataFormatter.formatCellValue(row.getCell(0)).trim(); // 用户ID在第一列
                    this.username = username;
                    this.password = password;
                    loginAttempts = 0; // 登录成功，重置尝试次数
                    return true; // 登录成功
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        loginAttempts++; // 错误尝试次数增加
        if (loginAttempts >= 5) {
            isLocked = true; // 错误次数达到5次，锁定账户
            System.out.println("登录失败次数过多，账户已被锁定。");
        } else {
            System.out.println("用户名或密码错误。还有 " + (5 - loginAttempts) + " 次尝试机会。");
        }
        return false; // 登录失败
    }

    // 辅助方法，用于获取单元格的字符串值
    private String getCellStringValue(Cell cell) {
        if (cell == null) {
            return ""; // 空单元格返回空字符串
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim(); // 返回字符串并去除空格
            case NUMERIC:
                // 处理数字，您可以选择保留小数部分
                return String.valueOf(cell.getNumericCellValue()).trim(); // 可以考虑在这里使用 DecimalFormat 来格式化
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue()).trim(); // 返回布尔值的字符串表示
            case FORMULA:
                // 处理公式单元格
                return String.valueOf(cell.getNumericCellValue()).trim(); // 如果公式返回数字，转为字符串
            case BLANK:
                return ""; // 空白单元格返回空字符串
            default:
                return ""; // 对于其他类型，返回空字符串
        }
    }

    //将商品添加购物车
    public void addToCart(String productId, int quantity) {
        shoppingCart.addItem(productId, quantity);
    }
    //将商品从购物车中移除
    public void removeFromCart(String productId) {
        shoppingCart.removeItem(productId);
    }

    //修改购物车中商品数量
    public void modifyProductIn(String productId, int newQuantity) {
        shoppingCart.modifyItem(productId, newQuantity);
    }
    //结账
    public void checkout() {
        double totalAmount = 0.0;
        for (Item item : shoppingCart.getItems()) {
            totalAmount += item.getTotalPrice(); // 计算总金额
        }

        // 显示总金额并确认购买
        System.out.println("总金额为： " + totalAmount);
        System.out.println("确认结账吗？（yes/no）");

        Scanner scanner = new Scanner(System.in);
        String confirmation = scanner.nextLine();

        if ("yes".equalsIgnoreCase(confirmation)) {
            // 记录到购物历史
            historyRecord.addRecord("结账金额： " + totalAmount + "， 结账时间： " + System.currentTimeMillis());

            shoppingCart.clearCart(); // 清空购物车
            System.out.println("结账成功，购物车已清空。");
        } else {
            System.out.println("结账已取消。");
        }
    }

    //退出管理员登录
    public void logout() {
        System.out.println("已成功退出登录。");
        // 这里可以添加更多的退出逻辑，比如清除会话等
    }
}
